package cn.dnf.user.service.impl;

import cn.dnf.basic.constant.RegisterConstant;
import cn.dnf.basic.exception.BusinessException;
import cn.dnf.basic.jwt.JwtUtils;
import cn.dnf.basic.jwt.RsaUtils;
import cn.dnf.basic.util.HttpUtil;
import cn.dnf.basic.util.JsonResult;
import cn.dnf.basic.util.Md5Utils;
import cn.dnf.basic.util.StrUtils;
import cn.dnf.org.mapper.EmployeeMapper;
import cn.dnf.system.domain.Menu;
import cn.dnf.system.domain.Permission;
import cn.dnf.user.constant.WxConstants;
import cn.dnf.user.domain.Logininfo;
import cn.dnf.user.domain.User;
import cn.dnf.user.domain.WxUser;
import cn.dnf.user.dto.LoginDto;
import cn.dnf.user.dto.WxDto;
import cn.dnf.user.mapper.LogininfoMapper;
import cn.dnf.user.mapper.UserMapper;
import cn.dnf.user.mapper.WxUserMapper;
import cn.dnf.user.service.IloginService;
import cn.dnf.user.util.LoginData;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.security.PrivateKey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
@Service
public class LoginServiceImpl implements IloginService {
    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WxUserMapper wxUserMapper;
    @Override
    public Map<String, Object> account(LoginDto dto) {
        /**
         *  1.根据用户名和type查询loginInfo,
         *  2.如果存在,则判断密码是否正确
         *      2.1: 加密的. (你输入的密码+数据库的盐值)mds加密
         *             和数据库的密码对比
         *  3.如果不存在,则直接提示,用户名不存在
         */
        //2dcc85a7476f8750014d15990f369e87
        Logininfo logininfo = logininfoMapper.getLogininfoByDto(dto);
        if(logininfo==null){
            //用户不存在
            throw new BusinessException("账号或密码错误!");
        }
            //判断密码是否正确 加盐加密;
            String md5Password = Md5Utils.encrypByMd5(logininfo.getSalt()+dto.getPassword());
        System.out.println(md5Password);
        // 和数据库中的密码做对比
            if(!md5Password.equals(logininfo.getPassword())){
                throw new BusinessException("账号或密码错误!");
            }

            //没问题了,把数据保存在redis中,设置过期时间
        // 随机生成一个key(token)
        /*String token = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);

        //准备一个map
        HashMap<String,Object> map = new HashMap<>();
        map.put("token",token);
        //把盐值,和密码设置为null
        logininfo.setSalt(null);
        logininfo.setPassword(null);
        map.put("logininfo",logininfo);*/

        //使用jwt
        Map<String,Object> map = loginSuccessJwtHandle(logininfo);

        return map;
    }

    private Map<String, Object> loginSuccessJwtHandle(Logininfo logininfo) {
        try {
            LoginData loginData = new LoginData();
            loginData.setLogininfo(logininfo);
            Map<String, Object> map = new HashMap<>();
            //
            if(logininfo.getType()==0){//管理人员
                //返回当前登陆人的权限
                List<String> permissions = employeeMapper.getPermissionsByLogininfoId(logininfo.getId());

                //当前登录人所有菜单
                List<Menu> menus = employeeMapper.getMenusByLogininfoId(logininfo.getId());

                //存入LoginData
                loginData.setMenus(menus);
                loginData.setPermissions(permissions);

                //存入map
                map.put("permissions",permissions);
                map.put("menus",menus);

            }
            //加密
            //4.通过私钥对登录信息进行加密 - jwtToken串
            PrivateKey privateKey = RsaUtils.getPrivateKey(RsaUtils.class.getClassLoader().getResource("auth_rsa.pri").getFile());
            //将登陆人信息加密得到jwtToken串
            String jwtToken = JwtUtils.generateTokenExpireInMinutes(loginData, privateKey, 3000);

            map.put("token",jwtToken);
            map.put("logininfo",logininfo);

            return map;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public JsonResult weChat(String code) {
        /**
         * 之前有没有绑定过
         *  1.现根据code查询出token和openid
         *  2.根据openid
         *  3.openid存在,之前有绑定过,直接免密登录
         *
         * 如果openid不存在,就要重新生成数据,绑定.
         *
         */
        //1.现根据code查询出token和openid
        String jsonStr = HttpUtil.httpGet(WxConstants.GET_ACK_URL
                .replace("APPID",WxConstants.APPID)
                .replace("SECRET",WxConstants.SECRET)
                .replace("CODE",code));
        //获取token和openid
        //把json字符串转成json对象
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        String access_token = jsonObject.getString("access_token");
        String openid = jsonObject.getString("openid");

        //根据openid查询wxuser
        WxUser dbWxUser = wxUserMapper.loadByOpenid(openid);
        //如果wxuser不为空,并且绑定了用户
        if(dbWxUser!=null && dbWxUser.getUser_id()!=null){
            //直接免密登录

            //获取logininfo信息
            Logininfo logininfo = logininfoMapper.loadByUserId(dbWxUser.getUser_id());
          /*  //随机生成一个key(token)
            String token = UUID.randomUUID().toString();
            redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);*/

          /*  //准备一个map
            HashMap<String,Object> map = new HashMap<>();
            map.put("token",token);
            //把盐值,和密码设置为null
            logininfo.setSalt(null);
            logininfo.setPassword(null);
            map.put("logininfo",logininfo);*/

            //使用jwt
            Map<String,Object> map = loginSuccessJwtHandle(logininfo);



            return JsonResult.me().setResultObj(map);
        }else{//第一次扫码
            //
            String param = "?accessToken="+access_token+"&openId="+openid;
            return JsonResult.me().setMsg("绑定").setResultObj(param);
        }

    }

    @Override
    public JsonResult binder(WxDto dto) {
        //1.校验, 非空校验,验证码校验--超时, 是否正确,
        String phone = dto.getPhone();
        String verifyCode = dto.getVerifyCode();
        String accessToken = dto.getAccessToken();
        String openId = dto.getOpenId();
        if(StringUtils.isEmpty(phone)
            ||StringUtils.isEmpty(verifyCode)
                        ||StringUtils.isEmpty(accessToken)
                        ||StringUtils.isEmpty(openId)
                ){
                throw new BusinessException("参数不能为空");
        }

        Object obj = redisTemplate.opsForValue().get(phone + RegisterConstant.WXBINDER);
        if (obj==null){
            throw new BusinessException("验证码过期,请重新获取!");
        }

        if (!verifyCode.equalsIgnoreCase(obj.toString().split(":")[0])){
            throw new BusinessException("验证码输入错误,请重新输入!");
        }





        //2.wxuser,user,logininfo
        //向微信开放平台发送第三次请求.获取vxuser信息.
        String jsonObj = HttpUtil.httpGet(WxConstants.GET_USER_URL
                        .replace("ACCESS_TOKEN",accessToken)
                        .replace("OPENID",openId)
        );

        WxUser wxUser = jsonObj2WxUser(jsonObj);
        //通过手机号查询user信息,能查到:直接绑定.
        User dbUser = userMapper.findByPhone(phone);
        //通过手机号查询user信息,查不到:自己生成一个user,logininfo,再绑定.
        if(dbUser==null){
            //没有用手机号注册过,生成一个user对象,存值. 关联一个logininfo
            dbUser = phone2User(phone);
            //logininfo
            Logininfo dblogininfo = user2Logininfo(dbUser);

            //保存logininfo,返回自增主键
            logininfoMapper.save(dblogininfo);
            //保存user 把logininfo_id要放进去
            dbUser.setLogininfo_id(dblogininfo.getId());
            userMapper.save(dbUser);//返回自增主键

        }
        //绑定wxuser
        wxUser.setUser_id(dbUser.getId());
        wxUserMapper.save(wxUser);

        //通过user中的logininfoid查询logininfo
        Logininfo logininfo = logininfoMapper.loadById(dbUser.getLogininfo_id());

        //免密登录
        /*String token = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);

        //准备一个map
        HashMap<String,Object> map = new HashMap<>();
        map.put("token",token);
        //把盐值,和密码设置为null
        logininfo.setSalt(null);
        logininfo.setPassword(null);
        map.put("logininfo",logininfo);*/
        //使用jwt
        Map<String,Object> map = loginSuccessJwtHandle(logininfo);



        return JsonResult.me().setResultObj(map);


    }
    private  Logininfo user2Logininfo(User dbUser){
        Logininfo logininfo = new Logininfo();
        //设置type=1,普通用户
        logininfo.setType(1);
        BeanUtils.copyProperties(dbUser,logininfo);
        return logininfo;
    }




    private User phone2User(String phone){
        User user = new User();
        user.setUsername(phone);
        user.setPhone(phone);
        //生成一个盐值,密码
        String salt = StrUtils.getComplexRandomString(32);
        user.setSalt(salt);
        //生成一个密码
        String password = StrUtils.getComplexRandomString(6);
        //加密
        String dbPassword = Md5Utils.encrypByMd5(salt + password);
        user.setPassword(dbPassword);

        return user;
    }
    //返回一个wxuser对象
    private WxUser jsonObj2WxUser(String jsonObj){
        //把jsonobj转成json对象
        JSONObject jsonObject = JSONObject.parseObject(jsonObj);
        WxUser wxUser = new WxUser();
        wxUser.setAddress(jsonObject.getString("country"));
        wxUser.setHeadimgurl(jsonObject.getString("headimgurl"));
        wxUser.setNickname("xx");//昵称,特殊字符
        wxUser.setOpenid(jsonObject.getString("openid"));
        wxUser.setSex(jsonObject.getInteger("sex"));
        wxUser.setUnionid(jsonObject.getString("unionid"));

        return wxUser;
    }
}
